<template>
  <div>
    <div class="mr-10">
      <el-autocomplete
        v-model="filterText"
        class="search flex"
        style="width: 300px;"
        :placeholder="$t('ENTER_LOCATION_SEARCH')"
        clearable
        :fetch-suggestions="querySearchAsync"
        :hide-loading="true"
        @select="pointSelected"
      >
        <template slot-scope="{ item }">
          <div class="address-text">{{ item.name }}</div>
          <div class="address-text">
            {{ item.district || '--' }}
            {{ item.address && item.address.length ? ` | ${item.address}` : '' }}
          </div>
        </template>
      </el-autocomplete>
    </div>
  </div>
</template>

<script>
  import areaApi from '@/api/system/AreaApi'
  const mapConfig = window.__mapConfig__

  export default {
    data() {
      return {
        mapConfig: mapConfig,
        filterText: ''
      }
    },
    computed: {
      autoComplete() {
        return new AMap.Autocomplete({
          datatype: 'poi'
        })
      }
    },
    methods: {
      querySearchAsync(keyword, cb) {
        if (!keyword) return
        if (!mapConfig.onlineMap) {
          this.offlineSearch(keyword, cb)
        } else {
          this.onlineSearch(keyword, cb)
        }
      },
      onlineSearch(keyword, cb) {
        this.autoComplete.search(keyword, (status, result) => {
          // console.log('onlineSearch搜索结果', status, result)
          if (status === 'error') {
            this.$message.error(this.$t(result))
            return
          }
          if (status !== 'complete' || !result || result.info !== 'OK') {
            this.$message.error(this.$t('NO_SEARCH_RESULT'))
            return
          }
          const list = result.tips || []
          cb(list.filter(i => i.location))
        })
      },
      offlineSearch(keyword, cb) {
        areaApi.list({ keyword: keyword }).then(res => {
          // console.log('offlineSearch', res)
          const result = []
          res.forEach(i => {
            if (!i.x || !i.y) return
            result.push({
              ...i,
              name: i.areaName,
              district: i.areaName,
              address: i.label,
              location: {
                lng: i.x, lat: i.y
              }
            })
          })
          cb(result || [])
        }).catch(() => {
          this.$message.error(this.$t('NO_SEARCH_RESULT'))
        })
      },
      pointSelected(item) {
        console.log('pointSelected', item)
        this.filterText = item.name
        const { lng, lat } = item.location
        this.$emit('locatePoint', [lng, lat])
      }
    }
  }
</script>

<style scoped>
  .address-text {
    /* white-space: normal; */
    white-space: pre-wrap;
    word-break: break-word;
    text-align: justify;
  }
</style>
